const app = getApp();

Page({
  data: {
    loading: false,
    monthlyBonuses: [], // 每月奖励数据
    currentYear: new Date().getFullYear(),
    totalBonus: 0
  },

  onLoad() {
    wx.setNavigationBarTitle({
      title: '收入明细'
    });
    this.fetchMonthlyBonuses();
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.fetchMonthlyBonuses();
  },

  // 获取每月奖励明细
  fetchMonthlyBonuses() {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    if (!token || !riderId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    this.setData({ loading: true });

    // 获取当前年份的12个月数据
    const currentYear = this.data.currentYear;
    const monthlyData = [];
    let completedRequests = 0;
    let totalBonus = 0;

    // 循环获取12个月的数据
    for (let month = 1; month <= 12; month++) {
      // 创建月份字符串格式：xxxx-xx月
      const monthStr = `${currentYear}-${month.toString().padStart(2, '0')}月`;

      wx.request({
        url: `${ip}/api/platform/settlement/calculateRiderBonusByMonth?riderId=${riderId}&month=${monthStr}`,
        method: 'GET',
        header: {
          'Authorization': 'Bearer ' + token
        },
        success: (res) => {
          completedRequests++;
          
          if (res.data.code === 200) {
            const bonusAmount = parseFloat(res.data.data) || 0;
            totalBonus += bonusAmount;
            
            monthlyData.push({
              month: month,
              monthName: `${month}月`,
              bonus: bonusAmount.toFixed(2),
              monthStr: monthStr,
              year: currentYear
            });
          } else {
            monthlyData.push({
              month: month,
              monthName: `${month}月`,
              bonus: '0.00',
              monthStr: monthStr,
              year: currentYear
            });
          }

          // 所有请求完成后更新界面
          if (completedRequests === 12) {
            // 按月份排序
            monthlyData.sort((a, b) => a.month - b.month);
            
            this.setData({
              monthlyBonuses: monthlyData,
              totalBonus: totalBonus.toFixed(2),
              loading: false
            });
          }
        },
        fail: () => {
          completedRequests++;
          
          monthlyData.push({
            month: month,
            monthName: `${month}月`,
            bonus: '0.00',
            monthStr: monthStr,
            year: currentYear
          });

          if (completedRequests === 12) {
            monthlyData.sort((a, b) => a.month - b.month);
            
            this.setData({
              monthlyBonuses: monthlyData,
              totalBonus: totalBonus.toFixed(2),
              loading: false
            });
          }
        }
      });
    }
  },

  // 切换年份
  onYearChange(e) {
    const year = parseInt(e.detail.value);
    this.setData({
      currentYear: year,
      monthlyBonuses: [],
      totalBonus: 0
    });
    this.fetchMonthlyBonuses();
  },

  // 查看某月详细数据
  onMonthTap(e) {
    const monthData = e.currentTarget.dataset.month;
    wx.showModal({
      title: `${monthData.year}年${monthData.monthName}奖励`,
      content: `奖励金额：¥${monthData.bonus}`,
      showCancel: false,
      confirmText: '确定'
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.fetchMonthlyBonuses();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});
